package cn.chair.controller.admin;

import cn.chair.dao.ChairDao;
import cn.chair.entity.Chair;
import cn.chair.model.admin.ChairListResp;
import cn.chair.model.admin.ChairResp;
import cn.chair.service.DeviceService;
import cn.chair.service.OssService;
import cn.chair.util.SmallUtil;
import com.cfilmcloud.framework.privilege.api.model.LevelDetails;
import com.cfilmcloud.framework.privilege.api.model.UserProfile;
import com.google.zxing.EncodeHintType;
import life.innovation.builder.SqlBuilder;
import life.innovation.exception.*;
import life.innovation.model.Page;
import life.innovation.model.PageList;
import life.innovation.util.PagerUtil;
import net.glxn.qrgen.core.image.ImageType;
import net.glxn.qrgen.javase.QRCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value="chair")
public class ChairController {

    @Value("${qrcode.url}")
    private String qrCodeUrl;

    @Value("${aliyun.endpoint}")
    private String endpoint;
    @Value("${aliyun.bucketName}")
    private String bucketName;

    private static int IMAGE_SIZE_DEFAULT = 280;
    @Autowired
    @Lazy
    private ChairDao chairDao;

    @Autowired
    @Lazy
    private OssService ossService;

    @Autowired
    @Lazy
    private DeviceService deviceService;

    private static final Logger log = LoggerFactory.getLogger("appLogger");


    /**
     * 查询设备列表
     * @param merchantId
     * @param merchantName
     * @param chairCode
     * @param chairName
     * @param runStatus
     * @param page
     * @param countPerPage
     * @return
     * @throws DataReadException
     */
    @GetMapping(value="getChairs")
    public ChairListResp get(@RequestParam(required = false) Integer merchantId,
                             @RequestParam(required = false) String merchantName,
                             @RequestParam(required = false) String chairCode,
                             @RequestParam(required = false) String chairName,
                             @RequestParam(required = false) Integer runStatus,
                             @RequestParam(required = false,defaultValue = "1") int page,
                             @RequestParam(required = false,defaultValue = "20")int countPerPage,
                             UserProfile userProfile) throws DataReadException {
       LevelDetails levelDetails = userProfile.getLevelDetails();

         List<Integer> storeId = null;
        if(!SmallUtil.isEmpty(levelDetails.getStoreId())){
            List<String> stores = Arrays.asList(levelDetails.getStoreId().split(","));
            storeId = stores.stream().map(Integer::parseInt).collect(Collectors.toList());
        }

        ChairListResp resp = new ChairListResp();

        log.info("设备状态:"+runStatus);

       List<ChairListResp.ChairList> lists = chairDao.getQrcodeList(merchantId,merchantName,chairCode,chairName,storeId);


       log.info("list大小:"+lists.size());

       if(lists != null && lists.size()>0){


           for(int i=0;i<lists.size();i++){
               ChairListResp.ChairList chair = lists.get(i);
               if(runStatus == null) {
                   boolean flag = deviceService.getDeviceisRun(String.valueOf(chair.getId()));
                   if (flag) {
                       chair.setRunStatus(1);
                   }
               }else if(runStatus == 0){
                   if(chair.getRunStatus() == 2){
                       lists.remove(chair);
                       i--;
                   }
               }else if(runStatus == 1){
                   boolean flag = deviceService.getDeviceisRun(String.valueOf(chair.getId()));
                   if (flag) {
                       chair.setRunStatus(1);
                   }else{
                       lists.remove(chair);
                       i--;
                   }
               }else if(runStatus == 2){
                   if(chair.getRunStatus() == 0){
                       lists.remove(chair);
                       i--;
                       continue;
                   }
                   boolean flag = deviceService.getDeviceisRun(String.valueOf(chair.getId()));
                   if(flag){
                       lists.remove(chair);
                       i--;
                   }

               }
           }

//           for(ChairListResp.ChairList  chair:lists){
//
//           }
       }


       log.info("修改后的list"+lists.size());

        Page pagination = PagerUtil.process(page, countPerPage, lists.size());

        resp.setPagination(pagination);
        resp.setList(lists.subList((pagination.getPage() - 1) * countPerPage, Math.min(pagination.getPage() * countPerPage, lists.size())));
       return resp;

    }

    @PostMapping(value="addChair")
    @Transactional
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void add(@RequestParam String chairCode,
                    @RequestParam (required = false,defaultValue = "")String chairName,
                    @RequestParam String chairType,
                    @RequestParam String merchantId) throws DataWriteException, UnauthorizedException, InvalidInputException, IOException, InterruptedException {

     List<Chair> list = chairDao.find(SqlBuilder.init().where("chair_code",chairCode)
             .where("merchant_id",merchantId));
    if(list!=null&&list.size()>0){
        throw new InvalidInputException("该座椅已存在");
    }

     Chair chair = new Chair();
     chair.setSeq(0);
     chair.setName(chairCode);
     if(!("").equals(chairName.trim())){
         chair.setDescription(chairName);
     }
     chair.setStatus(0);
     chair.setMerchantId(merchantId);
     chair.setChairCode(chairCode);
     chair.setChairType(chairType);
     chair.setRunStatus(0);
     chair.setPersonStatus(0);

     chairDao.insert(chair);

        String url = qrCodeUrl+chair.getId();
        File file = QRCode.from(url).to(ImageType.PNG)
                .withSize(IMAGE_SIZE_DEFAULT, IMAGE_SIZE_DEFAULT)
                .withHint(EncodeHintType.MARGIN, 3)
                .file();
        int font = 18;
        int startX = 90;
        int startY = 275;
        Image src = ImageIO.read(file);
        int imageW = src.getWidth(null);
        int imageH = src.getHeight(null);
        BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.createGraphics();
        g.drawImage(src, 0, 0, imageW, imageH, null);
        g.setColor(Color.BLACK);
        g.setFont(new Font("Times New Roman", Font.PLAIN, font));
        g.drawString(chairCode, startX, startY);
        g.dispose();

        FileOutputStream out = new FileOutputStream(file.getParent()+"/"+file.getName());
        if(ImageIO.write(image, "PNG", out)){
             file = new File(file.getParent()+"/"+file.getName());
            log.info("上传图片:"+file);
            ossService.uploadObject2OSS(file,chair.getId()+".png");
        }

        chair.setId(chair.getId());
        String imageUrl = "https://"+bucketName+"."+endpoint+"/"+chair.getId()+".png";
        chair.setImageUrl(imageUrl);

        chairDao.update(chair);
    }

    @GetMapping(value="{id}")
    public ChairResp getById(@PathVariable int id) throws ResourceNotFoundException {
        Chair chair = chairDao.findOne(SqlBuilder.init().where("id",id));
        if(chair == null){
            throw  new ResourceNotFoundException("error.chair.missing");
        }
        ChairResp resp = new ChairResp();
        resp.setId(chair.getId());
        resp.setChairCode(chair.getChairCode());
        resp.setChairName(chair.getDescription());
        resp.setChairType(chair.getChairType());
        resp.setMerchantId(chair.getMerchantId());
        return resp;
    }

    @GetMapping(value="updateChair/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void update(HttpServletRequest request,
                       @PathVariable int id,
                       @RequestParam String chairCode,
                       @RequestParam(required = false,defaultValue = "") String chairName,
                       @RequestParam String chairType,
                       @RequestParam String merchantId) throws ResourceNotFoundException, DataWriteException, UnauthorizedException {


        Chair chair = chairDao.findOne(SqlBuilder.init().where("id",id));
       if(chair == null){
           throw new ResourceNotFoundException("error.chair.missing");
       }

       chair.setChairCode(chairCode);
       chair.setName(chairCode);
       if(!chairName.trim().isEmpty()){
           chair.setDescription(chairName);
       }
       chair.setChairType(chairType);
       chair.setMerchantId(merchantId);
       chairDao.update(chair);
    }


}
